package com.ruoyi.basic.service.impl;

import java.util.Arrays;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.basic.constant.BasicConstants;
import com.ruoyi.basic.domain.BasicFamily;
import com.ruoyi.basic.domain.BasicUser;
import com.ruoyi.basic.mapper.BasicFamilyMapper;
import com.ruoyi.basic.mapper.BasicUserMapper;
import com.ruoyi.basic.service.IBasicFamilyService;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.common.core.text.Convert;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 家庭成员Service业务层处理
 * 
 * @author ruoyi
 * @date 2021-08-20
 */
@Service
public class BasicFamilyServiceImpl extends ServiceImpl<BasicFamilyMapper, BasicFamily> implements IBasicFamilyService
{

    @Autowired
    private BasicUserMapper userMapper;

    /**
     * 查询家庭成员
     * 
     * @param familyId 家庭成员主键
     * @return 家庭成员
     */
    @Override
    public BasicFamily selectBasicFamilyByFamilyId(Long familyId)
    {
        return baseMapper.selectBasicFamilyById(familyId);
    }

    /**
     * 查询家庭成员列表
     * 
     * @param basicFamily 家庭成员
     * @return 家庭成员
     */
    @Override
    public List<BasicFamily> selectBasicFamilyList(BasicFamily basicFamily)
    {
        return baseMapper.selectBasicFamilyList(basicFamily);
    }

    /**
     * 新增家庭成员
     * 
     * @param basicFamily 家庭成员
     * @return 结果
     */
    @Override
    public int insertBasicFamily(BasicFamily basicFamily)
    {
        basicFamily.setCreateTime(DateUtils.getNowDate());
        return baseMapper.insert(basicFamily);
    }

    /**
     * 修改家庭成员
     * 
     * @param basicFamily 家庭成员
     * @return 结果
     */
    @Override
    public int updateBasicFamily(BasicFamily basicFamily)
    {
        basicFamily.setUpdateTime(DateUtils.getNowDate());
        return baseMapper.updateById(basicFamily);
    }

    /**
     * 批量删除家庭成员
     * 
     * @param familyIds 需要删除的家庭成员主键
     * @return 结果
     */
    @Override
    public int deleteBasicFamilyByFamilyIds(String familyIds)
    {
        return baseMapper.deleteBatchIds(Arrays.asList(Convert.toLongArray(familyIds)));
    }

    /**
     * 删除家庭成员信息
     * 
     * @param familyId 家庭成员主键
     * @return 结果
     */
    @Override
    public int deleteBasicFamilyByFamilyId(Long familyId)
    {
        return baseMapper.deleteById(familyId);
    }

    /**
     * 导入用户家庭成员
     *
     * @param familyList 用户家庭成员数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importFamily(List<BasicFamily> familyList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(familyList) || familyList.size() == 0)
        {
            throw new ServiceException("导入用户家庭成员数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (BasicFamily family : familyList)
        {
            int row = 1;
            try
            {
                if(StringUtils.isEmpty(family.getFamilyName())){
                    continue;
                }
                //获取用户信息
                BasicUser user = userMapper.selectOne(new LambdaQueryWrapper<BasicUser>()
                        .eq(BasicUser::getIdCard, family.getIdCard()).last("limit 1"));
                if(StringUtils.isNotNull(user)) {
                    family.setUserId(user.getId());
                }else{
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、第 " + row + "行导入失败，员工 " + family.getUserName() + " 不存在");
                    continue;
                }
                // 验证是否存在这个用户
                BasicFamily u = baseMapper.selectOne(new LambdaQueryWrapper<BasicFamily>()
                        .eq(BasicFamily::getFamilyName, family.getFamilyName())
                        .eq(BasicFamily::getUserId, family.getUserId()));
                if (StringUtils.isNull(u))
                {
                    family.setCreateBy(operName);
                    this.insertBasicFamily(family);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、员工 " + family.getUserName() + " 家庭成员" + family.getFamilyName() + "导入成功");
                }
                else if (isUpdateSupport)
                {
                    family.setFamilyId(u.getFamilyId());
                    family.setUpdateBy(operName);
                    this.updateBasicFamily(family);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、员工 " + family.getUserName() + " 家庭成员" + family.getFamilyName() + "更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、员工 " + family.getUserName() + " 家庭成员" + family.getFamilyName() + "已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、员工 " + family.getUserName() + " 家庭成员导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
            finally {
                row++;
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 校验家庭成员是否唯一
     *
     * @param family 家庭成员信息
     * @return 结果
     */
    @Override
    public String checkFamilyNameUnique(BasicFamily family){
        Long familyId = StringUtils.isNull(family.getFamilyId()) ? -1L : family.getFamilyId();
        BasicFamily info = baseMapper.selectOne(new LambdaQueryWrapper<BasicFamily>()
                .eq(BasicFamily::getFamilyName, family.getFamilyId())
                .eq(BasicFamily::getUserId, family.getUserId()));
        if (StringUtils.isNotNull(info) && info.getFamilyId().longValue() != familyId.longValue())
        {
            return BasicConstants.FAMILY_NAME_NOT_UNIQUE;
        }
        return BasicConstants.FAMILY_NAME_UNIQUE;
    }
}
